<template>
  <div class="page-common-layout custom-tablePage-container">
    <div class="screen-conditions-container">
      <ScreenConditions :isDataType="false">
        <template slot="conditions">
          <AssociativeSelectGroup
            :map="selectMap"
            @conditionChange="selectGroupChange($event)"
          >
          </AssociativeSelectGroup>
        </template>
        <template slot="operate">
          <!-- <a-button class="cu-btn-primary" icon="search" @click="search()">
            查询
          </a-button>
          <a-button class="cu-btn-filter" icon="reload" @click="reset()">
            重置
          </a-button> -->
        </template>
      </ScreenConditions>
    </div>
    <div class="table-body-container">
      <div class="table-operate">
        <a-button
          @click="importTemplate()"
          class="cu-btn-primary margin-bottom-xs"
          icon="file-add"
          :loading="importLoading"
          :disabled="buttonStatus == 0 ? false : true"
          v-action:sjjhgl_add
        >
          批量导入
        </a-button>
        <input
          accept=".xls,.xlsx"
          @change="importExcel"
          type="file"
          ref="upload"
          id="upload"
          style="display: none"
        />
        <a-button
          @click="downloadTemplate()"
          class="cu-btn-primary margin-bottom-xs"
          icon="download"
        >
          下载模版
        </a-button>
      </div>
      <div class="table-main">
        <vxe-table
          ref="xTable"
          height="99%"
          align="center"
          show-overflow
          show-header-overflow
          border="inner"
          :data="tableData"
          :column-config="{ resizable: true }"
          size="small"
          :loading="loading"
          :tree-config="{
            rowField: 'uuid',
            parentField: 'pid',
            childrenField: 'childList',
          }"
        >
          <vxe-column field="nodeName" title="名称" tree-node align="left">
            <template #default="{ row }">
              <icon-fonts icon="icon-wenjianjia-" class="tree-icon" />
              {{ row.nodeName }}
            </template>
          </vxe-column>
          <vxe-column title="状态">
            <template #default="{ row }">
              <span
                class="state"
                :class="[filterClassName(row.status)]"
                v-if="row.pid == 0"
              >
                {{ filterStatusName(row.status) }}
              </span>
            </template>
          </vxe-column>
          <vxe-column field="planDate" title="计划提交时间"> </vxe-column>
          <vxe-column
            field="operate"
            width="140"
            title="操作"
            fixed="right"
            align="left"
          >
            <template #default="{ row }">
              <div class="text-button-group">
                <a-tooltip
                  placement="top"
                  v-if="row.status == 0"
                  v-action:sjjhgl_add
                >
                  <template slot="title">
                    新增子节点
                  </template>
                  <icon-font
                    type="icon-xinzengxiaji"
                    class="node-icon"
                    @click="handleAddChild(row)"
                  />
                </a-tooltip>
                <!-- 编辑 -->
                <a-tooltip
                  placement="top"
                  v-if="row.status == 0"
                  v-action:sjjhgl_edit
                >
                  <template slot="title">
                    编辑
                  </template>
                  <a-icon
                    type="edit"
                    class="edit-btn"
                    @click="handleEdit(row)"
                  />
                </a-tooltip>
                <!-- 删除 -->
                <a-tooltip
                  placement="top"
                  v-if="row.pid != 0 && row.status == 0"
                  v-action:sjjhgl_delete
                >
                  <template slot="title">
                    删除
                  </template>
                  <a-icon
                    type="delete"
                    class="delete-btn"
                    @click="handleDelClick(row)"
                  />
                </a-tooltip>
              </div>
            </template>
          </vxe-column>
        </vxe-table>
      </div>
    </div>
    <!-- 新增 -->
    <addModal
      :visible.sync="addModal.visible"
      :parameter="currentRow"
      :operateType="currentType"
    ></addModal>

    <editParentModal
      :visible.sync="editParentModal.visible"
      :parameter="currentRow"
    ></editParentModal>
  </div>
</template>

<script>
import { Icon } from "ant-design-vue";
import iconfrontjs from "@/assets/IconFont/iconfont.js";
const iconFrontUrl = iconfrontjs;
const IconFont = Icon.createFromIconfontCN({
  scriptUrl: iconFrontUrl,
});
import { axios } from "@/utils/request";
import { mapGetters } from "vuex";
import { getToken, downloadDfs } from "@/utils/TopVUI";
import { downLoadFileByArraybuffer, getParentNodeByKey } from "@/utils/util";
import ScreenConditions from "@/components/extendCustom/ScreenConditions";
import AssociativeSelectGroup from "@/components/extendCustom/AssociativeSelectGroup";
//新增
import addModal from "./components/addModal.vue";
//父节点编辑
import editParentModal from "./components/editParentModal.vue";
import {
  designPlanTree,
  designPlanTemplate,
  importDesignPlan,
  deleteBaseTree,
} from "@/api/knowledgeBase.js";
export default {
  components: {
    IconFont,
    ScreenConditions,
    AssociativeSelectGroup,
    addModal,
    editParentModal,
  },
  data() {
    return {
      selectMap: [
        //项目
        {
          type: "proCode",
          mode: "default",
          placeholder: "请选择项目",
          isDefault: true,
        },
      ],
      conditionsData: {},
      //列表
      loading: false,
      tableData: [],
      importLoading: false,
      //新增
      addModal: {
        visible: false,
      },
      currentRow: {},
      currentType: 1,
      buttonStatus: "",
      //父节点编辑
      editParentModal: {
        visible: false,
      },
    };
  },
  computed: {
    ...mapGetters(["configData"]),
    kkFileView() {
      let index = this.configData.findIndex(
        (item) => item.code === "kkFileView"
      );
      if (index >= 0) {
        return this.configData[index].value;
      } else {
        return "http://192.168.1.216:8012/onlinePreview";
      }
    },
  },

  methods: {
    handleAddChild(row) {
      this.currentRow = row;
      this.currentType = 1;
      this.addModal.visible = true;
    },
    handleEdit(row) {
      this.currentType = 2;
      if (row.pid == 0) {
        this.currentRow = row;
        this.editParentModal.visible = true;
      } else {
        let parentNode = getParentNodeByKey(
          row.uuid,
          "uuid",
          this.tableData,
          "childList"
        );
        this.currentRow = { parentName: parentNode.nodeName, ...row };
        this.addModal.visible = true;
      }
    },

    //模版下载
    downloadTemplate() {
      designPlanTemplate()
        .then((res) => {
          downLoadFileByArraybuffer(res, "设计计划管理模版.xlsx");
        })
        .catch((_) => {});
    },
    //导入
    importTemplate() {
      this.$refs.upload.click();
    },
    importExcel(event) {
      let { proCode } = this.conditionsData;
      let files = event.target.files;
      let formdata = new FormData();
      for (let i = 0; i < files.length; i++) {
        formdata.append("uploadFile", files[i]);
      }
      this.importLoading = true;
      importDesignPlan(formdata, proCode)
        .then((res) => {
          if (res.statusCode == 200 || res == 1) {
            this.$message.success("导入成功", 1.5);
            this.getTreeData();
          } else {
            this.$message.error(res.message);
          }
        })
        .catch((_) => {})
        .finally((_) => {
          event.target.value = "";
          this.importLoading = false;
        });
    },
    selectGroupChange(data) {
      this.dealConditionsData(data);
      this.getTreeData();
    },

    //处理搜索区域选中值
    dealConditionsData(data = {}) {
      Object.keys(data).forEach((key) => {
        if (!data[key]) {
          this.conditionsData[key] = "";
        } else if (Array.isArray(data[key])) {
          this.conditionsData[key] = data[key]
            .map((v) => v.key)
            .filter((v) => v)
            .toString();
        } else if (
          Object.prototype.toString.call(data[key]) === "[object Object]"
        ) {
          this.conditionsData[key] = data[key].key;
        } else {
          this.conditionsData[key] = "";
        }
      });
    },

    getTreeData() {
      this.loading = true;
      let { proCode } = this.conditionsData;
      designPlanTree({
        tenantCode: proCode,
        type: 4,
      })
        .then((res) => {
          this.tableData = res?.data?.list || [];
          this.buttonStatus = res?.data?.status;
        })
        .catch((_) => {
          this.tableData = [];
        })
        .finally((_) => {
          this.loading = false;
        });
    },
    //删除
    handleDelClick(row) {
      let that = this;
      that.$confirm({
        title: "提示",
        content: "确定删除该数据吗？删除之后不可恢复！",
        okText: "确定",
        cancelText: "取消",
        icon: () =>
          that.$createElement("a-icon", {
            props: {
              key: "warning",
              type: "exclamation-circle",
              twoToneColor: "#faad14",
            },
          }),
        onOk() {
          deleteBaseTree({ uuid: row.uuid })
            .then((res) => {
              if (res.statusCode === 200 || res === 1) {
                that.$message.success("删除成功", 1.5);
                that.getTreeData();
              } else {
                that.$message.error(res.message);
              }
            })
            .catch((_) => {});
        },
      });
    },

    //预览
    handeViewFile(row) {
      this.filePreview.fileList = this.analysisPath(row.surveyFile);
      this.filePreview.visible = true;
    },

    analysisPath(files = "[]") {
      let list = JSON.parse(files ?? "[]");
      return list;
    },

    filterStatusName(status) {
      switch (status) {
        case 0:
          return "待提交";

        case 1:
          return "审批中";

        case 2:
          return "已驳回";

        case 3:
          return "已完成";

        default:
          return "-";
      }
    },

    filterClassName(status) {
      switch (status) {
        case 0:
          return "default";

        case 1:
          return "warning";

        case 2:
          return "error";

        case 3:
          return "success";

        default:
          return "default";
      }
    },
  },
};
</script>

<style lang="less" scoped>
.table-body-container {
  .tree-icon {
    color: #f3ab1f;
  }
  .node-icon {
    color: #1677ff;
  }
  .state {
    &::before {
      content: "";
      display: inline-block;
      width: 8px;
      height: 8px;
      border-radius: 50%;
      margin-right: 10px;
    }
    &.warning {
      &::before {
        background: #f07f17;
      }
    }
    &.error {
      &::before {
        background: #ff2d2d;
      }
    }
    &.success {
      &::before {
        background: #239b53;
      }
    }
    &.default {
      &::before {
        background: #8c8c8c;
      }
    }
  }
}
</style>
